package com.project.controller;

import com.project.utils.Result;
import com.project.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam("image") MultipartFile file){
        if (file == null || file.isEmpty()) {
            System.out.println("文件为空");
            return Result.error("文件为空");
        }
        log.info("文件名上传，原始文件名:{}", file.getOriginalFilename());
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取文件后缀
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //生成一个UUID文件名
            String objectName = UUID.randomUUID().toString() + substring;
            //上传到阿里云,并返回文件路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败{}",e);
        }
        return Result.error("文件上传失败");
    }
}
